package com.hsmw.api.controller.forman;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.config.jwt.LoginUser;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.vo.WebSocketReturnVO;
import com.hsmw.common.base.BasePage;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.hsmw.common.base.BaseController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户邀请记录表 前端控制器
 * </p>
 *
 * @author wd
 * @since 2021-11-10
 */
@RestController
    @RequestMapping("/api/invite")
public class HsmwInviteRecordController extends BaseController<HsmwInviteRecordService, HsmwInviteRecord> {

    @Autowired
    private HsmwInviteRecordService hsmwInviteRecordService;
    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;
    @Autowired
    private HsmwInviteRecordMapper hsmwInviteRecordMapper;
    @Autowired
    private HsmwPushInfoService hsmwPushInfoService;


    @ApiOperation(value = "新增邀请信息 inviteType: 1. 公司邀请调度 2. 公司邀请合作公司 3. 搅拌站邀请自营 4.  搅拌站邀请合作 5. 公司公司邀请工长6. 公司邀请负责人 7. 搅拌站邀请工长 8. 搅拌站请负责人9. 搅拌站邀请调度 10. 搅拌站邀请调度",notes = "新增邀请信息",produces = "application/json")
    @PostMapping("/saveOrUpdateInviteInfo")
    public DataResponse saveOrUpdateInviteInfo(@RequestBody HsmwInviteRecord record){
        return  hsmwInviteRecordService.saveOrUpdateInviteInfo(record);
    }

    @ApiOperation(value = "重新邀请员工",notes = "重新邀请员工",produces = "application/json")
    @PostMapping("/reInviteInfo")
    public DataResponse reInviteInfo(@RequestBody HsmwInviteRecord record){
        DataResponse response = hsmwInviteRecordService.reInviteInfo(record);
        return  response;
    }

    @ApiOperation(value = "查询邀请记录 1. 公司邀请调度 2. 公司邀请合作公司 3. 搅拌站邀请自营 4.  搅拌站邀请合作5. 公司公司邀请工长  6. 公司邀请负责人  7 搅拌站邀请工长  8. 搅拌站邀请负责人 9.  搅拌站邀请调度 ",notes = "查询邀请记录 ",produces = "application/json")
    @PostMapping("/queryInviteInfoList")
    public DataResponse queryInviteInfoList(String  type ){
        List<HsmwInviteRecord> records = hsmwInviteRecordService.queryInviteList(type);
        return  new DataResponse(records);
    }


    @ApiOperation(value = "删除邀请记录 或者取消邀请",notes = "删除邀请记录 或者取消邀请",produces = "application/json")
    @PostMapping("/removeInviteInfo")
    public DataResponse removeInviteInfo(@RequestBody HsmwInviteRecord record){
        try {
            HsmwInviteRecord recordInfo  =hsmwInviteRecordMapper.selectById(record.getId());
            if(StringUtils.isNull(recordInfo)){
                return new DataResponse("操作成功");
            }
            if(InviteStatusEnum.RECEIVED.getValue().equals(recordInfo.getInviteStatus())){
                return new DataResponse(CommonConstants.ResponseStatus.INVITE_STATUS_CHANGE,null);
            }
            hsmwInviteRecordMapper.deleteById(record.getId());
            //删除推送的信息
            hsmwPushInfoService.remove(new LambdaQueryWrapper<HsmwPushInfo>()
                    .eq(HsmwPushInfo::getInvitedId,record.getId()));
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"删除邀请记录失败，请联系管理员！");
        }
        return new DataResponse();
    }

    @ApiOperation(value = "移除邀请人",notes = "移除邀请人",produces = "application/json")
    @PostMapping("/removeStuff")
    public DataResponse removeStuff(@RequestBody HsmwInviteRecord record){
        try {
            return hsmwInviteRecordService.removeStuff(record);

        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"移除邀请人失败，请联系管理员！");
        }
    }


    @ApiOperation(value = "查询邀请信息",notes = "查询邀请信息",produces = "application/json")
    @PostMapping("/queryInvitePushInfo")
    public DataResponse queryInvitePushInfo(){
        try {
            LoginUser loginUser = currentHsmwUserUtils.getCurrentUserInfo();
            List<HsmwPushInfo> infos = hsmwPushInfoService.list(new LambdaQueryWrapper<HsmwPushInfo>()
                    .eq(HsmwPushInfo::getForemanId, loginUser.getId())
                    .eq(HsmwPushInfo::getStatus, "0")
                    .notIn(HsmwPushInfo::getType, PushTypeEnum.DRIVER_REPORT.getValue(),PushTypeEnum.UPDATE_TIME.getValue()));
            List<WebSocketReturnVO> list = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(infos)){
                for (HsmwPushInfo one : infos) {
                    WebSocketReturnVO webSocketReturnVO = new WebSocketReturnVO();
                    webSocketReturnVO.setPushId(one.getId());
                    webSocketReturnVO.setInvitedId(one.getInvitedId());
                    webSocketReturnVO.setInvitedUserName(one.getInvitedUserName());
                    webSocketReturnVO.setMessage(one.getMessage());
                    webSocketReturnVO.setInvitedCompanyName(one.getInvitedCompanyName());
                    webSocketReturnVO.setInvitedName(one.getInvitedName());
                    webSocketReturnVO.setPushType(one.getType());
                    webSocketReturnVO.setType(one.getType());
                    webSocketReturnVO.setItemName(one.getInvitedItemName());
                    list.add(webSocketReturnVO);
                }
            }
            return new DataResponse(list);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询邀请信息失败，请联系管理员！");
        }
    }


    @ApiOperation(value = "同意或者拒绝邀请信息",notes = "同意邀请信息",produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "推送ID", name = "pushId", dataType = "String"),
            @ApiImplicitParam(value = "操作类型 0 拒绝 1 同意 ", name = "operType", dataType = "String")
    })
    @PostMapping("/receiveOrRejectInviteInfo")
    public DataResponse receiveOrRejectInviteInfo(String pushId,String  operType){
        try {
            if(StringUtils.isBlank(pushId)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "推送ID不能为空，请重新输入！");
            }
            if(StringUtils.isBlank(operType)){
                return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "同意或拒绝不能为空，请重新输入！");
            }
            HsmwPushInfo pushInfo = hsmwPushInfoService.getById(pushId);
            if(StringUtils.isNull(pushInfo) && CommonConstants.YES.equals(operType)){
                return new DataResponse(CommonConstants.ResponseStatus.INVITE_STATUS_CHANGE, "邀请状态已经改变，请刷新页面！");
            }

            return hsmwInviteRecordService.receiveOrRejectInviteInfo(pushId,operType);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"同意邀请信息失败，请联系管理员！");
        }
    }


    @ApiOperation(value = "搅拌站邀请自营公司的重新选择 公司ID 和公司名称不能为空",notes = "同意邀请信息",produces = "application/json")
    @PostMapping("/concreteRechooseCompany")
    public DataResponse concreteRechooseCompany(@RequestBody HsmwInviteRecord record){
        if(StringUtils.isBlank(record.getCompanyId())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "公司ID不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(record.getCompanyName())){
            return new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED, "公司名称不能为空，请重新输入！");
        }
        return hsmwInviteRecordService.concreteRechooseCompany(record);
    }


    @ApiOperation(value = "将项目工长的信息 转为 项目的联系人",notes = "将项目工长的信息 转为 项目的联系人",produces = "application/json")
    @PostMapping("/changeForemanToLinkMan")
    public DataResponse changeForemanToLinkMan(){
     /*   List<HsmwItemLinkman> linkmanList = hsmwItemLinkmanMapper.selectList(new LambdaQueryWrapper<>());
        List<HsmwItemLinkmanRelation> relations  = new ArrayList<>();

        for(HsmwItemLinkman foreman :linkmanList){
            HsmwItemLinkmanRelation relation = new HsmwItemLinkmanRelation();
            relation.setItemId(foreman.getItemId());
            relation.setLinkmanId(foreman.getId());
            hsmwItemLinkmanRelationMapper.insert(relation);
        }*/

    /*    //插入项目联系人
        List<HsmwHtnUser> foremanList = hsmwHtnUserService.list(new LambdaQueryWrapper<HsmwHtnUser>()
                .eq(HsmwHtnUser::getType,HtnUserTypeEnum.FOREMAN.getValue()));
        for(HsmwHtnUser user :foremanList){
            HsmwItemLinkman linkman = new HsmwItemLinkman();
            linkman.setPhoneNum(user.getUsername());
            linkman.setName(user.getName());
            linkman.setId(user.getId());
            HsmwItemLinkman linkman1  = hsmwItemLinkmanService.getById(user.getId());
            if(StringUtils.isNull(linkman1)){
                hsmwItemLinkmanService.save(linkman);
            }
        }
        //插入项目联系人 关系表
        List<HsmwItemLinkman> linkmanList = hsmwItemLinkmanService.list();
        for(HsmwItemLinkman user :linkmanList){
            List<HsmwForcemanItem> forcemanItems = hsmwForcemanItemMapper.selectList(new LambdaQueryWrapper<HsmwForcemanItem>()
                    .eq(HsmwForcemanItem::getForcemanId,user.getId()));
            if(CollectionUtil.isNotEmpty(linkmanList)){
                for(HsmwForcemanItem item :forcemanItems){
                    HsmwItemLinkmanRelation relation = new HsmwItemLinkmanRelation();
                    relation.setItemId(item.getItemId());
                    relation.setLinkmanId(user.getId());
                    hsmwItemLinkmanRelationMapper.insert(relation);
                }
            }
        }*/
      /*  List<HsmwReceiveOrderPrice> orderPrices = new ArrayList<>();

        HsmwDictType dictType = hsmwDictTypeService.getOne(new LambdaQueryWrapper<HsmwDictType>()
                .eq(HsmwDictType::getDictType,"sys_xb_type"));
        //根据前端传过来的中文的车辆型号翻译为 数据库中存储的车辆型号
        List<HsmwDictData> vehicleTypes =hsmwDictDataService.list(new LambdaQueryWrapper<HsmwDictData>()
                .eq(HsmwDictData::getDictType,"sys_xb_type")
                .orderByAsc(HsmwDictData::getDictValue));
        List<HsmwLeasingCompany > companies = hsmwLeasingCompanyService.list();
        for(HsmwDictData data :vehicleTypes){
            for(HsmwLeasingCompany company :companies){
                HsmwReceiveOrderPrice price = new HsmwReceiveOrderPrice();
                price.setSettlePrice(new BigDecimal("17.00"));
                price.setCompanyId(company.getId());
                price.setCompanyType("1");
                price.setVehicleType(dictType.getDictName());
                price.setVehicleModel(data.getDictLabel());
                orderPrices.add(price);
                hsmwReceiveOrderPriceMapper.insert(price);
            }
        }*/
/*
        List<HsmwReceiveOrderPrice> orderPrices = new ArrayList<>();

        HsmwDictType dictType = hsmwDictTypeService.getOne(new LambdaQueryWrapper<HsmwDictType>()
                .eq(HsmwDictType::getDictType,"sys_xb_type"));
        //根据前端传过来的中文的车辆型号翻译为 数据库中存储的车辆型号
        List<HsmwDictData> vehicleTypes =hsmwDictDataService.list(new LambdaQueryWrapper<HsmwDictData>()
                .eq(HsmwDictData::getDictType,"sys_xb_type")
                .orderByAsc(HsmwDictData::getDictValue));
        List<HsmwLeasingCompany > companies = hsmwLeasingCompanyService.list();

        List<HsmwConcretePlantInfo > plantInfos= hsmwConcretePlantInfoMapper.selectList(new LambdaQueryWrapper<>());
        for(HsmwDictData data :vehicleTypes){
            for(HsmwConcretePlantInfo company :plantInfos) {
                HsmwReceiveOrderPrice price = new HsmwReceiveOrderPrice();
                price.setSettlePrice(new BigDecimal("17.00"));
                price.setCompanyId(company.getId());
                price.setCompanyType("2");
                price.setSettleType("1");
                price.setVehicleType(dictType.getDictName());
                price.setVehicleModel(data.getDictLabel());
                hsmwReceiveOrderPriceMapper.insert(price);
            }
                for(HsmwLeasingCompany company1 :companies){
                    HsmwReceiveOrderPrice price1 = new HsmwReceiveOrderPrice();
                    price1.setSettlePrice(new BigDecimal("17.00"));
                    price1.setCompanyId(company1.getId());
                    price1.setCompanyType("1");
                    price1.setSettleType("1");
                    price1.setVehicleType(dictType.getDictName());
                    price1.setVehicleModel(data.getDictLabel());
                    hsmwReceiveOrderPriceMapper.insert(price1);
                }

        }
      */
      /*  List<HashMap> values = new ArrayList<>();
        HashMap value = new HashMap();
        value.put("name","3年以内");
        value.put("value",2);
        values.add(value);
        HashMap value2 = new HashMap();
        value2.put("name","3-5年");
        value2.put("value",0);
        values.add(value2);


        HashMap value3 = new HashMap();
        value3.put("name","5-7年");
        value3.put("value",-2);
        values.add(value3);


        HashMap value4 = new HashMap();
        value4.put("name","7-10年");
        value4.put("value",-5);
        values.add(value4);


        HashMap value5 = new HashMap();
        value5.put("name","18点-6点");
        value5.put("value",1);
        values.add(value5);

        List<HsmwLeasingCompany > companiess = hsmwLeasingCompanyService.list();
        for(HashMap map :values){
            for(HsmwLeasingCompany company1 :companiess){
                HsmwReceiveSubsidyPrice price1 = new HsmwReceiveSubsidyPrice();
                price1.setSettlePrice(new BigDecimal((Integer)map.get("value")));
                price1.setCompanyId(company1.getId());
                price1.setCompanyType("1");
                price1.setSettleType("1");
                price1.setTimeBetween((String) map.get("name"));
                hsmwReceiveSubsidyPriceMapper.insert(price1);
            }
        }*/


        return new DataResponse();
    }






}

